package cn.tedu.weibo.controller;

import cn.tedu.weibo.entity.User;
import cn.tedu.weibo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    private UserMapper mapper;

    @RequestMapping("/regA")
    public int regA(@RequestBody User user){
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            return 2;
        }
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/loginA")
    public int loginA(@RequestBody User user, HttpServletResponse response, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u==null){
            return 2;
        }
        if (!u.getPassword().equals(user.getPassword())){
            return 3;
        }
        //记住登录状态
        session.setAttribute("user",u);

        if(user.getRem()) {
            Cookie c1 = new Cookie("username", u.getUsername());
            Cookie c2 = new Cookie("password", u.getPassword());
            //设置cookie保存时间
            c1.setMaxAge(60 * 60 * 24 * 30);
//        c2.setMaxAge(60*60*24);

            //把cookie下发给客户端
            response.addCookie(c1);
            response.addCookie(c2);
        }
            return 1;

    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //把登录成功时保存的用户对象取出返回给客户端, 如果没有登录u为null
        User u = (User) session.getAttribute("user");
        return u;
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登陆成功时保存的用户对象
        session.removeAttribute("user");
    }


}
